<template>
    <view class="page-box">
        <header :class="['header row bothSide', info.level == 1 ? 'level-color1' : info.level == 3 ? 'level-color3' : info.level == 4 ? 'level-color4' : '']">
            <view class="row verCenter">
                <view class="pic">
                    <image :src="info.wx_photo_base64" mode="aspectFill"></image>
                </view>
                <view class="text">
                    <navigator class="t1" url="/pages/mine/setting" hover-class="none">{{info.name}}</navigator>
                    <navigator class="t2" url="/pages/mine/setting" hover-class="none" v-if="info.company">{{info.company}}</navigator>
                    <text class="label row rowCenter verCenter">{{info.level_val}}</text>
                </view>
            </view>
            <template v-if="info.level == 1">
                <image src="../../static/zuanshi-1.png" class="identity-identification" mode="aspectFill"></image>
            </template>
            <template v-else-if="info.level == 3">
                <image src="../../static/wanzhe-1.png" class="identity-identification" mode="aspectFill"></image>
            </template>
            <template v-else-if="info.level == 4">
                <image src="../../static/hehuoren-1.png" class="identity-identification" mode="aspectFill"></image>
            </template>
        </header>
        <section class="section">
            <view class="account-information">
                <view class="info row bothSide" :class="[info.level == 1 ? 'level1' : info.level == 3 ? 'level3' : info.level == 4 ? 'level4' : '']">
                    <view class="column">
                        <text class="t1">账户余额</text>
                        <text class="price">{{yuEInfo.yue || 0}}</text>
                    </view>
                    <view class="column">
                        <navigator class="row verCenter" url="/pages/bank/index" hover-class="none">
                            <text class="iconfont icon-juxing1"></text>
                            <text class="t2">银行卡号</text>
                        </navigator>
                        <navigator class="withdrawal row rowCenter verCenter" :url="'/pages/bank/withdraw?balance='+yuEInfo.yue" hover-class=" none">提现</navigator>
                    </view>
                </view>
                <view class="bottom row  verCenter">
                    <view class="column">
                        <text class="t1">个人本月进件(笔)</text>
                        <text class="t2">{{yuEInfo.orderCount || 0}}</text>
                    </view>
                    <view class="column">
                        <text class="t1">个人本月账单(元)</text>
                        <text class="t2">{{yuEInfo.billCount || 0}}</text>
                    </view>
                </view>
            </view>
            <view class="business-management">
                <view class="title">业务管理</view>
                <view class="links-box row avarage verCenter">
                    <navigator class="box column rowCenter verCenter" url="/pages/order/achievement" hover-class="none">
                        <image src="http://www.szxlyc.com/uploads/product/20241108/be5c8e1d794fe96fd9fedbe1cc31474f.png"></image>
                        <text>业绩管理</text>
                    </navigator>
                    <navigator class="box column rowCenter verCenter" url="/pages/order/team" hover-class="none">
                        <image src="http://www.szxlyc.com/uploads/product/20241108/9a831f33bfa789d0b0f4097679c11527.png"></image>
                        <text>团队管理</text>
                    </navigator>
                    <navigator class="box column rowCenter verCenter" url="/pages/bank/myIncome" hover-class="none">
                        <image src="http://www.szxlyc.com/uploads/product/20241108/8fb725cc2563cd1e8d8a4b7fb42b861a.png"></image>
                        <text>我的收入</text>
                    </navigator>
                    <navigator class="box column rowCenter verCenter" url="/pages/mine/point" hover-class="none">
                        <image src="http://www.szxlyc.com/uploads/product/20241108/5a77e5d237aaf2af652397c73745b8ae.png"></image>
                        <text>我的积分</text>
                    </navigator>
                </view>
            </view>
            <view class="list column">
                <!-- 钻石用户隐藏邀请码 -->
                <view class="box row bothSide verCenter" v-if="info.level != 1" @click="invitation()">
                    <text class="title">我的邀请码</text>
                    <image class="arrow" src="../../static/jiantou.png" mode="aspectFill"></image>
                </view>
                <navigator class="box row bothSide verCenter" url="/pages/mine/myIncome" hover-class="none">
                    <text class="title">我的收入报告</text>
                    <image class="arrow" src="../../static/jiantou.png" mode="aspectFill"></image>
                </navigator>
                <navigator class="box row bothSide verCenter" :url="'/pages/mine/myProductList?channel_user_id='+info.channel_user_id" hover-class="none">
                    <text class="title">我的产品超市</text>
                    <image class="arrow" src="../../static/jiantou.png" mode="aspectFill"></image>
                </navigator>
                <navigator class="box row bothSide verCenter" url="/pages/admin/list" hover-class="none" v-if="info.is_audit == 1">
                    <text class="title">进件审核管理</text>
                    <image class="arrow" src="../../static/jiantou.png" mode="aspectFill"></image>
                </navigator>
            </view>
        </section>
        <!-- 弹窗提示 -->
        <uni-popup ref="popup" background-color="#fff" borderRadius="20rpx">
            <view class="popup-content column rowCenter verCenter">
                <view class="content column">
                    <template v-if="imageSrc">
                        <image :src="imageSrc" style="width: 686rpx;height: 1120rpx;margin: 0 auto;border-radius: 20rpx;"></image>
                    </template>
                    <template v-else>
                        <canvas id="myCanvas" canvas-id="myCanvas" style="width: 686rpx;height: 1120rpx;margin: 0 auto;opacity: 0;border-radius: 20rpx;"></canvas>
                    </template>
                </view>
                <view class="iconfont icon-a-tubiaochangyongsousuo9" @click="close()"></view>
            </view>
        </uni-popup>
        <watermark :company="company" :name="name" :phoneLastDigits="phoneLastDigits" />
    </view>

</template>

<script>
    import { API } from '@/util/api.js';
    import { setCookie, getCookie } from '@/util/util.js';

    export default {
        data() {
            return {
                name: '',
                phoneLastDigits: '',
                company: '',
                userParams: {
                    openId: '',
                    name: '',
                    nickname: '',
                    avatar: '',
                    email: '',
                    invite_id: ''
                },
                inviteCodePic: '', //邀请的二维码
                imageSrc: '', //canvas生成个人邀请码图片
                info: {}, //个人信息
                yuEInfo: {} //账单信息
            };
        },
        onLoad(options) {
            //微信授权获取携带过来的客户信息字段
            this.userParams.openId = options.openId || '';
            this.userParams.name = options.name || '';
            this.userParams.nickname = options.nickname || '';
            this.userParams.avatar = options.avatar || '';
            this.userParams.email = options.email || '';
            this.userParams.invite_id = options.invite_id || '';

            console.log('微信菜单栏携带的参数：' + JSON.stringify(options));

            //判断微信公共账号菜单点击个人中心 或者 首次关注 从推送的注册链接点击个人中心
            if (this.userParams.openId) {
                this.checkOpenIdIsExists();
            } else {
                //初步判断是否登录
                var token = getCookie('app_user_id');
                console.log('token：' + token);
                if (!token) {
                    window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx82dd5de1c159bb98&redirect_uri=http://www.szxlyc.com/open/wx/oauth?target=5&response_type=code&scope=snsapi_userinfo&code=CODE&state=STATE#wechat_redirect   '
                }
            }
        },
        onShow() {
            //如果不携带openId则走正常逻辑
            if (!this.userParams.openId) {
                this.getData();
                this.getUserYuEInfo();
            }
        },
        methods: {
            /**
             * 微信跳转后判断openid
             */
            checkOpenIdIsExists() {
                this.request(API.checkOpenIdIsExists, 'GET', { openId: this.userParams.openId }, true).then(res => {
                    console.log('判断openId返回数据：' + JSON.stringify(res));
                    if (res.code === 0) {
                        setCookie('app_user_id', res.data.app_user_id, 30); //自动登录设置cookie
                        uni.showLoading({
                            mask: true
                        });
                        setTimeout(() => {
                            uni.hideLoading();
                            this.getData();
                            this.getUserYuEInfo();
                        }, 500)
                    } else {
                        //该微信用户暂未绑定程序
                        uni.navigateTo({
                            url: '/pages/mine/login?openId=' + this.userParams.openId + '&name=' + this.userParams.name + '&nickname=' + this.userParams.nickname + '&avatar=' + this.userParams.avatar + '&email=' + this.userParams.email + '&invite_id=' + this.userParams.invite_id
                        });
                    }
                });
            },
            getData() {
                this.request(API.getUserInfo, 'GET', {}, false).then(res => {
                    if (res.code === 0) {
                        setCookie('channel_user_id', res.data.channel_user_id, 30); //设置用户的渠道id
                        setCookie('level', res.data.level, 30); //设置用户的等级
                        this.getInvite(); //获取邀请二维码
                        this.info = res.data;

                        this.name = res.data.name;
                        this.company = res.data.company;
                        // 截取电话号码的后4位
                        this.phoneLastDigits = res.data.tel.slice(-4);

                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 获取邀请二维码
             */
            getInvite() {
                this.request(API.invite, 'GET', {}, false).then(res => {
                    if (res.code === 0) {
                        this.inviteCodePic = res.data;
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 获取用户余本月账单个人进件数
             */
            getUserYuEInfo() {
                this.request(API.getUserYuEInfo, 'get', {}, false).then(res => {
                    if (res.code === 0) {
                        this.yuEInfo = res.data;
                    } else {
                        uni.showToast({
                            title: res.msg,
                            icon: 'none'
                        });
                    }
                });
            },
            /**
             * 邀请码弹窗
             */
            invitation() {
                this.$refs.popup.open('center');

                if (!this.imageSrc) {
                    uni.showLoading({
                        mask: true,
                        title: '图片生成中...'
                    });
                    this.$nextTick(() => {
                        setTimeout(() => {
                            this.drawCanvas();
                        }, 800)
                    });
                }
            },
            /**
             * 关闭弹窗
             */
            close() {
                this.$refs.popup.close();
            },
            /**
             * 初始化海报
             */
            drawCanvas() {
                console.log('开始绘制图片');
                const query = uni.createSelectorQuery().in(this);

                // 使用exec获取画布的真实宽高
                query.select('#myCanvas').fields({ node: true, size: true }).exec((res) => {
                    if (!res || res.length === 0) {
                        console.error('Failed to get canvas context');
                        return;
                    }

                    // 获取canvas宽高
                    const { width, height } = res[0];

                    // 获取canvas上下文
                    const ctx = uni.createCanvasContext('myCanvas', this);

                    // 使用动态获取的宽高绘制
                    this.drawRoundRect(ctx, 0, 0, width, height, 0, 10);

                    // 绘制背景图
                    this.drawRoundImage(ctx, '../../static/yaoqima.png', 0, 0, width, height, 10);


                    ctx.setFontSize(13);
                    ctx.setFillStyle('#C1CCFF');
                    ctx.font = '13px PingFangSC';
                    const t1 = '更好的车金融产品尽在小朗优创'
                    let t1Width = ctx.measureText(t1).width;
                    ctx.fillText(t1, (width - t1Width) / 2, 58);


                    ctx.setFontSize(14);
                    ctx.setFillStyle('#FFFFFF');
                    ctx.font = 'bold 14px PingFangSC';
                    const t2 = '人无我有，人有我新，人新我专，人专我恒'
                    let t2Width = ctx.measureText(t2).width;
                    ctx.fillText(t2, (width - t2Width) / 2, 88);


                    ctx.setFontSize(13);
                    ctx.setFillStyle('#C1CCFF');
                    ctx.font = '13px PingFangSC';
                    const t3 = '让车抵贷产品和您之间更透明、更体贴'
                    let t3Width = ctx.measureText(t2).width - 30;
                    ctx.fillText(t3, (width - t3Width) / 2, 118);

                    // 绘制白色线条
                    ctx.setFillStyle('rgba(255, 255, 255, 0.1)');
                    const lineWidth = width * 0.85;
                    const lineX = (width - lineWidth) / 2;
                    const lineY = 148;
                    ctx.fillRect(lineX, lineY, lineWidth, 1); // 1px高的线条

                    // 绘制文字部分
                    ctx.setFontSize(11);
                    ctx.setFillStyle('#FFFFFF');
                    ctx.font = '11px PingFangSC';
                    ctx.fillText('运营支持', 30, 180);
                    ctx.setFillStyle('#C1CCFF');
                    ctx.fillText('| 智能匹配系统+人工服务跟进', 80, 180);

                    ctx.setFillStyle('#FFFFFF');
                    ctx.fillText('财务支持', 30, 200);
                    ctx.setFillStyle('#C1CCFF');
                    ctx.fillText('| 佣金快速到账+不跳单不卡佣', 80, 200);

                    ctx.setFillStyle('#FFFFFF');
                    ctx.fillText('产品支持', 30, 220);
                    ctx.setFillStyle('#C1CCFF');
                    ctx.fillText('| 热门贷款产品+明星大咖私人定制服务', 80, 220);

                    // 绘制白色区域 (居中)
                    const rectWidth = 274;
                    const rectHeight = 296;
                    const rectX = (width - rectWidth) / 2;
                    const rectY = 250;
                    this.drawRoundRect(ctx, rectX, rectY, rectWidth, rectHeight, 8);

                    // 头像和用户名在一行水平居中
                    const avatarSize = 44;
                    ctx.setFontSize(14);
                    ctx.setFillStyle('#2E3233');
                    const nameText = this.info.name || '用户名';
                    const nameTextWidth = ctx.measureText(nameText).width;
                    const padding = 10; // 头像和用户名之间的间距

                    // 计算头像和用户名总宽度，并水平居中
                    const totalWidth = avatarSize + padding + nameTextWidth;
                    const startX = (width - totalWidth) / 2;

                    // 绘制头像
                    const avatarX = startX;
                    const avatarY = rectY + 20; // 相对于白色区域的顶部
                    this.drawRoundImage(ctx, this.info.wx_photo_base64, avatarX, avatarY, avatarSize, avatarSize, avatarSize / 2);

                    // 绘制用户名，头像右侧
                    const nameTextX = avatarX + avatarSize + padding;
                    ctx.fillText(nameText, nameTextX, avatarY + avatarSize / 2 + 5);

                    // 二维码区域
                    const qrCodeSize = 170;
                    const qrCodeX = (width - qrCodeSize) / 2;
                    const qrCodeY = avatarY + avatarSize + 10;
                    ctx.drawImage(this.inviteCodePic, qrCodeX, qrCodeY, qrCodeSize, qrCodeSize);

                    // 绘制提示文本
                    ctx.setFontSize(10);
                    ctx.setFillStyle('#6E767A');
                    const t4 = '发展客户，建立团队、轻松玩转车金融';
                    const t4Width = ctx.measureText(t4).width;
                    ctx.fillText(t4, (width - t4Width) / 2, qrCodeY + qrCodeSize + 20);

                    // 画布绘制完成
                    ctx.draw(false, () => {
                        setTimeout(() => {
                            this.convertCanvasToImage();
                        }, 500)
                    });
                });
            },
            drawRoundRect(ctx, x, y, width, height, radius) {
                ctx.setFillStyle('#FFFFFF');
                ctx.beginPath();
                ctx.moveTo(x + radius, y);
                ctx.arcTo(x + width, y, x + width, y + height, radius);
                ctx.arcTo(x + width, y + height, x, y + height, radius);
                ctx.arcTo(x, y + height, x, y, radius);
                ctx.arcTo(x, y, x + width, y, radius);
                ctx.closePath();
                ctx.fill();
            },
            /**
             * 绘制圆角图片
             */
            drawRoundImage(ctx, imagePath, x, y, width, height, radius) {
                ctx.save(); // 保存当前绘图上下文的状态

                // 创建圆角路径
                ctx.beginPath();
                ctx.moveTo(x + radius, y);
                ctx.arcTo(x + width, y, x + width, y + height, radius);
                ctx.arcTo(x + width, y + height, x, y + height, radius);
                ctx.arcTo(x, y + height, x, y, radius);
                ctx.arcTo(x, y, x + width, y, radius);
                ctx.closePath();

                // 裁剪路径
                ctx.clip();

                // 在圆角区域内绘制图片
                ctx.drawImage(imagePath, x, y, width, height);

                ctx.restore(); // 恢复之前保存的绘图上下文的状态
            },
            /**
             * 转图片
             */
            convertCanvasToImage() {
                uni.hideLoading();
                uni.canvasToTempFilePath({
                    canvasId: 'myCanvas',
                    quality: 1,
                    success: (res) => {
                        this.imageSrc = res.tempFilePath;
                        console.log('图片渲染成功');
                    },
                    fail: (error) => {
                        uni.showToast({
                            title: '将画布转换为图片失败',
                            icon: 'none'
                        })
                        console.error('将画布转换为图片失败:', error);
                    }
                }, this);
            }
        }
    };
</script>

<style scoped lang="scss">
    @import '@/assets/css/mine/index.scss';
</style>